package org.utils.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.log4j.Logger;
import org.xml.sax.InputSource;

/**
 * @author Manuel EVENO
 */
public class XslTransformer
{
	public static XslTransformer instance = null;
	public static XslTransformer getInstance()
	{
		if (instance == null)
			instance = new XslTransformer();
		return instance;
	}
	private TransformerFactory tFactory = null;
	private Logger logger = null;
	/**
	 * Constructor for XslTransformer.
	 */
	public XslTransformer()
	{
		super();
		init();
	}
	/**
	 * Initialise the transformer Factory
	 */
	protected void init()
	{
		logger = Logger.getLogger(getClass());
		// Use the static TransformerFactory.newInstance() method to instantiate 
		// a TransformerFactory. The javax.xml.transform.TransformerFactory 
		// system property setting determines the actual class to instantiate
		logger.info("Initializing the transformer factory");
		tFactory = TransformerFactory.newInstance();
	}
	/**
	 * Handles the transformation
	 * @param in The input stream
	 * @param xsl The xsl stream
	 * @param in The output stream (where to write the result)
	 */
	public void transform(String in, String xsl, String out) throws TransformerException, IOException
	{
		transform(
			new FileInputStream(in),
			new FileInputStream(xsl),
			new FileOutputStream(out)
		);
	}
	/**
	 * Handles the transformation
	 * @param in The input stream
	 * @param xsl The xsl stream
	 * @param in The output stream (where to write the result)
	 */
	public void transform(File in, File xsl, File out) throws TransformerException, IOException
	{
		transform(
			new FileInputStream(in),
			new FileInputStream(xsl),
			new FileOutputStream(out)
		);
	}
	/**
	 * Handles the transformation
	 * @param in The input stream
	 * @param xsl The xsl stream
	 * @param in The output stream (where to write the result)
	 */
	public void transform(InputStream in, InputStream xsl, OutputStream out) throws TransformerException
	{
		// Use the TransformerFactory to instantiate a Transformer that will work with  
		// the stylesheet you specify. This method call also processes the stylesheet
		// into a compiled Templates object.
		logger.debug("Creating transformer");
		Transformer transformer = tFactory.newTransformer(new StreamSource(xsl));
		// Use the Transformer to apply the associated Templates object to an XML document
		logger.debug("Applying XSL Stylesheet to input stream");
		transformer.transform(new SAXSource(new InputSource(in)), new StreamResult(out));
	}
}
